package cn.online.taxi.api.listen.message;

import cn.online.taxi.api.listen.controller.WebSocketController;
import com.alibaba.fastjson.JSONObject;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.Date;
import java.util.Map;
import java.util.Set;

@EnableScheduling //开启定时器功能
@Component
public class MessageSender {

    @Scheduled(fixedRate = 5000) //间隔2s 通过StringRedisTemplate对象向redis消息队列chat频道发布消息
    public void sendMessage() {
        Set<Map.Entry<String, Session>> entries = WebSocketController.sessionMap.entrySet();
        if (entries.size() <= 0) {
            return;
        }
        for (Map.Entry<String, Session> entry : entries) {
            Session value = entry.getValue();
            if (value != null) {
                JSONObject data = new JSONObject();
                data.put("ping", Long.valueOf(new Date().getTime()));
                value.getAsyncRemote().sendText(data.toString());
            }
        }
    }
}
